package com.stefanhermann.particlestest;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class ParticlesTestActivity extends Activity {
	
	ParticlesSurfaceView mySurfaceView;
   
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mySurfaceView = new ParticlesSurfaceView(this);
        setContentView(mySurfaceView);
    }
    
    
    
    
    @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mySurfaceView.pause();
	}




	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mySurfaceView.resume();
	}




	class ParticlesSurfaceView extends SurfaceView implements Runnable {
    	
    	//#### Variables
    	SurfaceHolder ourSurfaceHolder;
    	Thread myThread;
    	boolean isRunning = false;
    	ParticleEmitter particles1;

		public ParticlesSurfaceView(Context context) {
			super(context);
			ourSurfaceHolder = getHolder();
			
			//Set up particle emitter
			particles1 = new ParticleEmitter();
			particles1.setPosition(300, 400);
			particles1.setVelocity(0, 200, 20);
			particles1.initialize();
			
			resume();
			// TODO Auto-generated constructor stub
		}
		
		public void resume(){
			isRunning = true;
			myThread = new Thread(this);
			myThread.start();
		}
		
		
		
		public void pause(){
			isRunning = false;
			while(true){
				try {
					myThread.join();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			}
		}

		public void run() {
			
			while(isRunning){
				if(!ourSurfaceHolder.getSurface().isValid())
					continue;
				
				//Set canvas
				Canvas canvas = ourSurfaceHolder.lockCanvas();
				canvas.drawRGB(200, 200, 200);
				
				particles1.update(canvas);
				
				ourSurfaceHolder.unlockCanvasAndPost(canvas);
			}
		}
    	
    }
}